﻿(function (window, document) {
  'use strict';
  function loadStyles() {
    var tag = document.createElement('link'),
      head = document.getElementsByTagName('head')[0];
    tag.href = 'https://albooka.googlecode.com/hg/styles.css';
    tag.rel = 'stylesheet';
    tag.type = 'text/css';

    head.appendChild(tag);
  }

  function setBtn(el, ref) {
    var span = document.createElement('div'),
      youCalendarDiv = document.createElement('div'),
      in12ClicksDiv = document.createElement('div'),
      logoImg = document.createElement('img'),
      calendarImg = document.createElement('img');

    el.className += ' albooka-btn';

    span.style.cssText = 'display: inline-block; vertical-align: top';

    youCalendarDiv.innerHTML = 'свой календарь';
    in12ClicksDiv.innerHTML = 'за 5 минут';
    logoImg.src = 'https://albooka.googlecode.com/hg/images/logo.png';
    logoImg.height = 27;
    logoImg.width = 89;
    logoImg.style.cssText = 'border: 0; display: inline-block; vertical-align: top';
    span.appendChild(youCalendarDiv);
    span.appendChild(in12ClicksDiv);
    span.appendChild(logoImg);

    calendarImg.src = 'https://albooka.googlecode.com/hg/images/calendar.png';
    calendarImg.height = 67;
    calendarImg.width = 66;
    calendarImg.style.cssText = 'border: 0; position: relative; top: -12px; vertical-align: top; float: right';
    el.href = 'http://c.albooka.com' + (ref
      ? '?from=' + encodeURI(ref)
      : '');
    el.target = '_blank';
    el.innerHTML = '';
    el.appendChild(span);
    el.appendChild(calendarImg);
  }

  function albooka(el, ref) {
    if (el) {
      var node, startsWith = el[0];

      switch (startsWith) {
      case '#':
        node = document.getElementById(el.slice(1));
        node && setBtn(node, ref);
        break;
      case '.':
        node = document.getElementsByClassName(el.slice(1));
        node && node.length && setBtn(node[0], ref);
        break;
      default:
        node = document.getElementsByTagName(el);
        node && node.length && setBtn(node[0], ref);
        break;
      }
    }
  }

  loadStyles();
  window.albooka = albooka;
}(window, document));